/*
 * @Description: 
 * @Autor: 万洲
 * @Date: 2022-10-24 15:37:28
 * @LastEditors: 万洲
 * @LastEditTime: 2022-11-21 15:00:11
 */
import { reqGetRoutes } from "@/api/System";
import router from "@/router";
import { IUserRouteListItem } from "@/types/system/IUserRouteListItem";
import { IUserInfo } from "@/types/user/IUserApiResponse";
import { defineStore } from "pinia";
import { computed, reactive, ref, toRefs } from "vue";
import Layout from '@/views/Layout/index'
const useUserStore = defineStore("userStore", () => {
    const userInfo = ref({} as IUserInfo)
    const userRoutes = ref<IUserRouteListItem[]>([])
    const userToken = ref<string | undefined>(undefined)

    /**
     * 设置用户token
     */
    const setToken = (token: string | undefined) => {
        userToken.value = token
    }
    /**
     * 设置用户信息
     * @param value 用户信息
     * @returns 
     */
    const setUserInfo = (value: IUserInfo) => userInfo.value = value
    /**
     * 用户登出
     */
    const loginOut = () => {
        userToken.value = undefined
        userRoutes.value = []
        router.replace("/login")
    }
    const getRoutes = async () => {
        if (userRoutes.value[0]) return userRoutes.value
        let result = await reqGetRoutes()
        userRoutes.value = result.data
        return result.data
    }
    return {
        userInfo,
        userRoutes,
        userToken, setToken, loginOut, setUserInfo, getRoutes
    }
}, {
    // 开启状态持久化
    persist: true,
})
export default useUserStore

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap: IUserRouteListItem[], lastRouter?: IUserRouteListItem, type?: boolean) {
    return asyncRouterMap.filter(route => {
        if (type && route.children) {
            route.children = filterChildren(route.children)
        }
        if (route.component) {
            // Layout ParentView 组件特殊处理
            if (route.component === 'Layout') {
                route.component = Layout
            } else {
                route.component = loadView(route.component)
            }
        }
        if (route.children != null && route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children, route, type)
        } else {
            delete route?.children
            delete route['redirect']
        }
        return true
    })
}

function filterChildren(childrenMap: IUserRouteListItem[], lastRouter?: any) {
    var children: IUserRouteListItem[] = []
    childrenMap.forEach((el, index) => {
        if (el.children && el.children.length) {
            if (el.component === 'ParentView' && !lastRouter) {
                el.children.forEach(c => {
                    c.path = el.path + '/' + c.path
                    if (c.children && c.children.length) {
                        children = children.concat(filterChildren(c.children, c))
                        return
                    }
                    children.push(c)
                })
                return
            }
        }
        if (lastRouter) {
            el.path = lastRouter.path + '/' + el.path
        }
        children = children.concat(el)
    })
    return children
}

// 动态路由遍历，验证是否具备权限


export const loadView = (view: string) => {
    if (process.env.NODE_ENV === 'development') {
        return (resolve: any) => require([`@/views/${view}`], resolve)
    } else {
        // 使用 import 实现生产环境的路由懒加载
        return () => import(`@/views/${view}`)
    }
}
